import { store } from "@/store"
import { usePermissionStoreHook } from "@/store/modules/permission"
// import { useDictStoreHook } from "@/store/modules/dict"

import { setToken, setRefreshToken, getRefreshToken, clearToken } from "@/utils/auth"
import { useStorageAsync } from "@vueuse/core"
import { defineStore } from 'pinia'
import { $http } from '@/service/request/index'

export const useUserStore = defineStore("user", () => {
  const userInfo = useStorageAsync("userInfo", {})

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData) {
    return new Promise((resolve, reject) => {
      $http('Login', loginData)
        .then(res => {
          if (res.code === 200) {
            const { token } = res.data
            setToken(token)
            resolve()
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  /**
   * 获取用户信息
   *
   * @returns {UserInfo} 用户信息
   */
  function getUserInfo() {
    return new Promise((resolve, reject) => {
      $http('getInfo')
        .then((data) => {
          if (!data || data.code !== 200) {
            reject("认证失败, 请重新登录！")
            return
          }
          Object.assign(userInfo.value, { ...data.data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise((resolve, reject) => {
      $http('Logout')
        .then(() => {
          clearUserData();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 刷新 token
   */
  function refreshToken() {
    const refreshToken = getRefreshToken();
    return new Promise((resolve, reject) => {
      AuthAPI.refreshToken(refreshToken)
        .then((data) => {
          const { tokenType, accessToken, refreshToken } = data;
          setToken(tokenType + " " + accessToken);
          setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          console.log(" refreshToken  刷新失败", error);
          reject(error);
        });
    });
  }

  /**
   * 清理用户数据
   *
   * @returns
   */
  function clearUserData() {
    return new Promise((resolve) => {
      clearToken()
      usePermissionStoreHook().resetRouter()
      // useDictStoreHook().clearDictionaryCache()
      resolve()
    })
  }

  return {
    userInfo,
    getUserInfo,
    login,
    logout,
    clearUserData,
    refreshToken
  }
})

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
